package cn.element.netty.experiment;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class HelloClient {

    public static void main(String[] args) throws InterruptedException {
        // 1.启动类
        new Bootstrap()
                .group(new NioEventLoopGroup())  // 2.添加EventLoop
                .channel(NioSocketChannel.class)  // 3.选择客户端channel实现
                .handler(new ChannelInitializer<NioSocketChannel>() {  // 4.添加处理器
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 5.初始话ChannelInitializer,并负责添加handler
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8080))  // 6.连接到服务器
                .sync()
                .channel()
                .writeAndFlush("Hello World!");  // 7.向服务器发送数据
    }

}
